package com.topscomm.mpm.utils;

import com.topscomm.pub.util.StringUtil;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * com.topscomm.mpm.utils
 * MengM_
 * 2021/8/16 20:20
 * mpm
 */
public class PdfToImageUtil {

    // 图片间的间距
    private static final int SEPARATE_DISTANCE = 0;

    public static int toImageFromByte(String imagePath, String imageNamePrefix, byte[] pdfByte, boolean needMergeImage) {
        return toImageFromByte(imagePath, imageNamePrefix, "png", pdfByte, needMergeImage);
    }

    public static int toImageFromByte(String imagePath, String imageNamePrefix, String imageType, byte[] pdfByte, boolean needMergeImage) {
        return toImageFromByte(imagePath, imageNamePrefix, imageType, pdfByte, 0, -1, needMergeImage);
    }

    public static int toImageFromByte(String imagePath, String imageNamePrefix, String imageType, byte[] pdfByte, int startPage, int endPage, boolean needMergeImage) {
        if (StringUtil.isEmpty(imagePath)) {
            return -1;
        }
        if (StringUtil.isEmpty(imageNamePrefix)) {
            return -1;
        }
        if (StringUtil.isEmpty(imageType)) {
            return -1;
        }
        if (pdfByte == null) {
            return -1;
        }
        if (!imageType.startsWith(".")) {
            imageType = "." + imageType;
        }
        // 去掉前缀中的 .
        if (imageNamePrefix.indexOf(".") > 0) {
            imageNamePrefix = imageNamePrefix.substring(0, imageNamePrefix.indexOf("."));
        }
        // 添加路径分隔符
        if (!imagePath.endsWith("/") && !imagePath.endsWith("\\")) {
            imagePath += File.separator;
        }

        try {
            File directory = new File(imagePath);
            directory.mkdirs();

            // 加载pdf
            PDDocument document = PDDocument.load(pdfByte);
            PDFRenderer renderer = new PDFRenderer(document);
            // pdf总页数
            int totalCount = document.getNumberOfPages();
            if (endPage == -1) {
                endPage = totalCount;
            }
            if (startPage == -1) {
                startPage = totalCount - 1;
            }
            List<File> fileList = null;
            if (needMergeImage) {
                fileList = new ArrayList<>();
            }
            for (int i = startPage; i < endPage; i++) {
                // dpi值越大越清晰，但是转换速度越慢
                BufferedImage image = renderer.renderImageWithDPI(i, 250);
                File file = new File(imagePath + imageNamePrefix + "_" + totalCount + "_" + (i + 1) + imageType);
                ImageIO.write(image, imageType.substring(1), file);
                if (needMergeImage) {
                    fileList.add(file);
                }
            }
            if (needMergeImage) {
                File file = new File(imagePath + imageNamePrefix + imageType);
                mergeMultiImageFiles(fileList, file);
            }
            return totalCount;
        } catch (IOException e) {
            e.printStackTrace();
            return -1;
        }
    }

    public static void mergeMultiImageFiles(List<File> imageFiles, File image)
            throws IOException {
        if (imageFiles != null && imageFiles.size() > 0) {
            BufferedImage imageNew = null;
            for (int i = 0; i < imageFiles.size(); i++) {
                BufferedImage imageBuffer = ImageIO.read(imageFiles.get(i));
                int width = imageBuffer.getWidth();
                int height = imageBuffer.getHeight();

                if (imageNew == null) {
                    imageNew = new BufferedImage(width, (height + SEPARATE_DISTANCE) * imageFiles.size(), BufferedImage.TYPE_INT_RGB);
                }

                int[] imageRgbArray = new int[width * height];
                imageRgbArray = imageBuffer.getRGB(0, 0, width, height, imageRgbArray, 0, width);

                imageNew.setRGB(0, (height + SEPARATE_DISTANCE) * i, width, height, imageRgbArray, 0, width);//SEPARATE_DISTANCE表示两张图片的间隔距离

            }
            ImageIO.write(imageNew, "png", image);
        }
    }
}
